package com.demo.miya.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author cyj
 **/
@Slf4j
@RestController
public class UploadController {

    private final static List<String> SUFFIX_NAMES = Lists.newArrayList("txt");

    @SneakyThrows
    @PostMapping("/upload")
    public JSONObject upload(@RequestParam("file") MultipartFile fileUpload){
        JSONObject json = new JSONObject();
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名
        String suffixName = StringUtils.substringAfterLast(fileName, ".");
        log.info("文件格式：{}", suffixName);
        if (!SUFFIX_NAMES.contains(suffixName.toLowerCase())) {
            json.put("error", "只支持上传txt文本");
            return json;
        }

        InputStream inputStream = fileUpload.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        StrBuilder builder = new StrBuilder();
        String tmp = null;
        while ((tmp = in.readLine()) != null) {
            builder.append(tmp);
        }
        log.info("文本内容：{}", builder);
        json.put("文本内容", builder.toString());
        return json;
    }

}
